using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Framework.Library.Core.Utils.Miscellaneous
{
    public static class EncryptionUtils
    {
        public static byte[] GenerateKey()
        {
            var provider = new RijndaelManaged();
            provider.GenerateKey();

            return provider.Key;
        }

        public static byte[] GenerateIV()
        {
            var provider = new RijndaelManaged();
            provider.GenerateIV();

            return provider.IV;
        }

        public static string Decrypt(byte[] encryptedBytes, byte[] key, byte[] iv)
        {
            var provider = new RijndaelManaged();

            var ms = new MemoryStream();

            using (var cryptoStream = new CryptoStream(ms, provider.CreateDecryptor(key, iv), CryptoStreamMode.Write))
            {
                cryptoStream.Write(encryptedBytes, 0, encryptedBytes.Length);
            }

            return Encoding.UTF8.GetString(ms.ToArray());
        }

        public static byte[] Encrypt(string value, byte[] key, byte[] iv)
        {
            var provider = new RijndaelManaged();
            byte[] valueBytes = Encoding.UTF8.GetBytes(value);

            var ms = new MemoryStream();

            using (var cryptoStream = new CryptoStream(ms, provider.CreateEncryptor(key, iv), CryptoStreamMode.Write))
            {
                cryptoStream.Write(valueBytes, 0, valueBytes.Length);
            }

            return ms.ToArray();
        }
    }
}